/**    
* @Title: OkexRestApi.java
* @Package: org.vdalf.gsgz.api.impl
* @author vDalf 2020-09-26 10:14:08 上午10:14:08
* @Copyright © 2020 vDalf Block-Chain Foundation (In Preparation Non-Governmental Organization) All rights reserved.
*/
package org.vdalf.gsgz.api.impl;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.vdalf.gsgz.config.OkexRobotProperties;
import org.vdalf.gsgz.utils.Constants;
import org.vdalf.gsgz.utils.MD5Utils;

import com.alibaba.fastjson.JSONObject;
import com.okcoin.commons.okex.open.api.bean.futures.param.Order;
import com.okcoin.commons.okex.open.api.bean.futures.result.OrderResult;
import com.okcoin.commons.okex.open.api.bean.swap.param.PpOrder;
import com.okcoin.commons.okex.open.api.bean.swap.result.SwapOrderResult;
import com.okcoin.commons.okex.open.api.utils.DateUtils;
import com.okcoin.commons.okex.open.api.utils.HmacSHA256Base64Utils;

/**    
* @Title: OkexRestApi.java
* @Package: org.vdalf.gsgz.api.impl
* @Description: 
* @author vDalf 2020-09-26 10:14:08 上午10:14:08
*/
@Service("okexRestApi")
public class OkexRestApi {
	
	private static final Logger logger = LoggerFactory.getLogger(OkexRestApi.class);
	
	@Autowired
	private OkexRobotProperties okexRobotProperties;
	
	@Autowired
	private RestTemplate restTemplate;
	
	public OrderResult doOrder(Order order) {
		logger.info("开始交割合约下单:order={}",order);
		try {
			String ts = DateUtils.getUnixTime();
			String body = JSONObject.toJSONString(order);
			HttpHeaders header = header(ts);
			sign(header, ts, "POST", okexRobotProperties.getServer().getFuturesOrderCommitUrl(), body);
//			logger.info("body--->{}",body);
//			logger.info("header--->{}",header);
			logger.info("发送API请求--->{}{}{}",okexRobotProperties.getServer().getHost(),okexRobotProperties.getServer().getFuturesOrderCommitUrl(),body);
			OrderResult resp = restTemplate.postForObject(okexRobotProperties.getServer().getHost()+okexRobotProperties.getServer().getFuturesOrderCommitUrl(),new HttpEntity<String>(body,header), OrderResult.class);
			logger.info("下单结果:{}",resp);
			return resp;
		} catch (Exception e) {
			logger.error("下单异常....",e);
			return null;
		}
	}
	
	public SwapOrderResult doOrder(PpOrder order) {
		logger.info("开始永续合约下单:order={}",order);
		try {
			String ts = DateUtils.getUnixTime();
			String body = JSONObject.toJSONString(order);
			HttpHeaders header = header(ts);
			sign(header, ts, "POST", okexRobotProperties.getServer().getSwapOrderCommitUrl(), body);
//			logger.info("body--->{}",body);
//			logger.info("header--->{}",header);
			logger.info("发送API请求--->{}{}{}",okexRobotProperties.getServer().getHost(),okexRobotProperties.getServer().getSwapOrderCommitUrl(),body);
			SwapOrderResult resp = restTemplate.postForObject(okexRobotProperties.getServer().getHost()+okexRobotProperties.getServer().getSwapOrderCommitUrl(),new HttpEntity<String>(body,header), SwapOrderResult.class);
			logger.info("下单结果:{}",resp);
			return resp;
		} catch (Exception e) {
			logger.error("下单异常....",e);
			return null;
		}
		
	}
	
	private HttpHeaders header(String ts) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-type","application/json");
		headers.add(Constants.OK_HEADER_OK_ACCESS_KEY,okexRobotProperties.getAccount().getApiKey());
		headers.add(Constants.OK_HEADER_OK_ACCESS_PASSPHRASE,okexRobotProperties.getAccount().getPassphrase());
		headers.add(Constants.OK_HEADER_OK_ACCESS_TIMESTAMP,String.valueOf(ts));
		return headers;
	}
	
	private void sign(HttpHeaders header,String ts,String method,String requestPath,String body) {
//		String plain = ts + method + requestPath+Optional.ofNullable(body).orElse("")+okexRobotProperties.getAccount().getSecretKey();
//		header.add(Constants.OK_HEADER_OK_ACCESS_SIGN,MD5Utils.md5(plain));
		try {
			header.add(Constants.OK_HEADER_OK_ACCESS_SIGN,HmacSHA256Base64Utils.sign(ts, method, requestPath, "", Optional.ofNullable(body).orElse(""), okexRobotProperties.getAccount().getSecretKey()));
		} catch (InvalidKeyException | UnsupportedEncodingException | CloneNotSupportedException e) {
			logger.error("e---->",e);
			throw new IllegalArgumentException("sign error:",e);
		}
		
	}


	
}
